program nc_reducer_51

    use iasing_osse
    use netcdf

    implicit none
    ! Program counters 
    integer :: iowrite
    integer :: jo, jl
    integer :: nobs
    integer, allocatable :: listObs(:)

    ! Netcdf stuff
    character(len=64) :: ncfile 
    integer :: ncid, ouid
    
    ! Interpolation
    real(JPR4) :: vprof(51)

    ! iasing_osse stuff
    type(r4a_ids) :: db_ids, ou_ids
    type(r54_dat) :: db_dat, ou_rec

    ! Interfaces
    include "checknc.interface"
    include "r60_initializer.interface"
    include "r60_reader.interface"
    include "r51_idscreator.interface"
    include "r51_writer.interface"
    
PENDING CREATE FUNCTIONS AND STRUCTURES FOR 54 LEVELS
FUNCTION TO CONVERT R6O TO R54 


    ! Read selected
    open(1,file='selected',status='old',action='read')
    read(1,'(A)') ncfile
    read(1,*) nobs
    allocate(listObs(nobs))
    read(1,*) listObs
    close (1)

    ! Create new file
    call checknc(nf90_create("example.nc", NF90_HDF5, ouid))
    ou_ids = r60_idscreator(ouid, nobs)
    call checknc(nf90_enddef(ouid))

    ! Print info
    print*, ncfile

    ! Open old netcdf Databank
    call checknc(nf90_open(ncfile, NF90_NOWRITE, ncid))
    db_ids = r60_initializer(ncid)

    do jo = 1, nobs
        db_dat  = r60_reader(ncid, db_ids, listObs(jo))
        
        ! Convert 
        
        
        
!~ 		! Change radiance units
!~         ! IASI
!~         if (any(db_dat%rbt%ria<=0. .or. db_dat%rbt%ria>1000.)) then
!~             db_dat%rbt%ria = -999.9
!~         else
!~             db_dat%rbt%ria = rad2brt_f(NIASI, db_dat%dim%wia, &
!~                 db_dat%rbt%ria)
!~         endif
!~         ! IASI-NG A
!~         if (any(db_dat%rbt%rng<=0. .or. db_dat%rbt%rng>1000.)) then
!~             db_dat%rbt%rng = -999.9
!~         else
!~             db_dat%rbt%rng = rad2brt_f(NIANG, db_dat%dim%wng, &
!~                 db_dat%rbt%rng)
!~         endif
!~         ! IASI-NG B
!~         if (any(db_dat%rbt%ngb<=0. .or. db_dat%rbt%ngb>1000.)) then
!~             db_dat%rbt%ngb = -999.9
!~         else 
!~             db_dat%rbt%ngb = rad2brt_f(NIANG, db_dat%dim%wng, &
!~                 db_dat%rbt%ngb)
!~         endif

        
!~         iowrite = r60_writer(ouid, ou_ids, jo, db_ids, db_dat)
        if (nobs>10.and.mod(jo,nobs/10).eq.0) print*, "Observation ", jo
    enddo

    ! Close Netcdf Databank
    call checknc(nf90_close(ncid))
    call checknc(nf90_close(ouid))

end program nc_reducer_51
